package controller

import (
	"danmu/common"
	"danmu/dto"
	"danmu/model"
	"danmu/response"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
)

func GetUserMessageList(ctx *gin.Context) {
	DB := common.GetDB()
	//从上下文中获取用户id
	id, _ := ctx.Get("id")
	var messageList []model.Message
	//过滤重复的消息
	//DB.Debug().Table("messages").Where("uid = ? " ,id.(uint)).Select("DISTINCT fid").Find(&messageList)
	//DISTINCT没法实现效果
	DB.Table("messages").Where("uid = ? ", id.(uint)).Find(&messageList)
	if len(messageList) != 0 {
		//对切片进行去重
		messageList = removeDuplicateElement(messageList)
		response.Success(ctx, gin.H{"data": dto.ToMessageListDto(messageList)}, "获取成功")
	} else {
		response.Success(ctx, gin.H{"data": nil}, "没有消息")
	}
}

func GetUserMessageById(ctx *gin.Context) {
	DB := common.GetDB()
	//从上下文中获取用户id
	id, _ := ctx.Get("id")
	var messageList []model.Message
	fid := ctx.DefaultQuery("fid", "0")
	if fid == "0" {
		response.Fail(ctx, nil, "消息不存在")
		return
	}
	DB.Table("messages").Where("uid = ? AND fid = ?", id.(uint), fid).Find(&messageList)
	//查询用户信息
	var userInfo model.User
	DB.First(&userInfo, fid)
	response.Success(ctx, gin.H{"face": userInfo.Face, "name": userInfo.Name, "data": dto.ToMessageByIdDto(messageList)}, "获取成功")
}

//发送私信
func SendUserMessage(ctx *gin.Context) {
	DB := common.GetDB()
	//获取参数
	var requestMsg = model.Message{}
	_ = ctx.Bind(&requestMsg)
	fid := requestMsg.Fid
	content := requestMsg.Content
	msgType := 2
	//从上下文中获取用户id
	id, _ := ctx.Get("id")
	if fid == 0 {
		response.Fail(ctx, nil, "发送失败")
		return
	}
	if fid == id.(uint) {
		response.Fail(ctx, nil, "不能发送给自己")
		return
	}
	var newUserMsg = model.Message{
		Uid:     id.(uint),
		Fid:     fid,
		FromId:  id.(uint),
		ToId:    fid,
		Content: content,
		MsgType: msgType,
	}
	DB.Create(&newUserMsg)
	//切换消息归属人
	//newUserMsg.Uid = fid
	//newUserMsg.Fid = id.(uint)
	var userMsg = model.Message{
		Uid:     fid,
		Fid:     id.(uint),
		FromId:  id.(uint),
		ToId:    fid,
		Content: content,
		MsgType: msgType,
	}
	DB.Create(&userMsg)
	response.Success(ctx, nil, "发送成功")
}

func GetUnreadMsg(ctx *gin.Context){
	//获取未读消息数
	DB :=common.GetDB()
	//从上下文中获取用户id
	id,_ :=ctx.Get("id")
	var announceCount int
	var messageCount int
	DB.Model(&model.AnnounceUser{}).Where("uid = ? AND status = ?" ,id,0).Count(&announceCount)
	DB.Model(&model.Message{}).Where("uid = ? AND status = ?" ,id,0).Count(&messageCount)
	//返回数据
	response.Success(ctx,gin.H{"announce":announceCount,"message":messageCount},"获取成功")
}

func MsgHaveRead(ctx *gin.Context){
	DB :=common.GetDB()
	//获取参数
	var requestMsg = model.Message{}
	err := ctx.Bind(&requestMsg)
	if err != nil{
		response.Response(ctx,http.StatusBadRequest,400,nil,"请求错误")
		return
	}
	fid := requestMsg.Fid
	//从上下文中获取用户id
	uid, _ := ctx.Get("id")
	DB.Model(&model.Message{}).Where("uid = ? AND fid = ?",uid,fid).Update("status",1)
	response.Success(ctx, nil, "已读成功")
}

func DeleteMessage(ctx *gin.Context){
	DB :=common.GetDB()
	//获取参数
	var requestMsg = model.Message{}
	err := ctx.Bind(&requestMsg)
	if err != nil{
		response.Response(ctx,http.StatusBadRequest,400,nil,"请求错误")
		return
	}
	fid := requestMsg.Fid
	//从上下文中获取用户id
	uid, _ := ctx.Get("id")
	DB.Where("uid = ? AND fid = ?",uid,fid).Delete(&model.Message{})
	response.Success(ctx, nil, "删除成功")
}

func removeDuplicateElement(messageList []model.Message) []model.Message {
	result := make([]model.Message, 0)
	//第一个数据肯定不会重复
	result = append(result, messageList[0])
	for i := 1; i < len(messageList); i++ {
		repeat := false
		for j := 0; j < len(result); j++ {
			if messageList[i].Fid == result[j].Fid {
				repeat = true
				//如果相同则保存时间较新的一个
				var newTime time.Time
				newTime = messageList[i].CreatedAt
				messageList[i].CreatedAt = result[j].CreatedAt
				result[j].CreatedAt = newTime
				break
			}
		}
		if !repeat {
			result = append(result, messageList[i])
		}
	}
	return result
}
